﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Protocols;
using System.Configuration;
using System.Linq;
using Yes.Application;
using Yes.Application.Article;
using Yes.Application.Article.Dto;
using Yes.Application.Category;
using Yes.Application.Comment;
using Yes.Application.Comment.Dto;
using Yes.Core.Extensions;
using Yes.Domain.Context;
using Yes.Domain.Entity;
using Yes.Domain.Enum;
using Yes.Web.Blog.Attribute;
using Yes.Web.Blog.Models;
using Yes.Web.Blog.Models.Article;

namespace Yes.Web.Blog.Controllers
{
    [AllowAnonymous]
    public class ArticleController : BaseController
    {
        private IConfiguration _configuration { get; }
        private ICategoryService _categoryService;
        private IArticleService _articleService;
        private ICommentService _commentService;
        private IUserContext _userContext;

        public ArticleController(ICategoryService categoryService, IArticleService articleService, ICommentService commentService, IUserContext userContext, IConfiguration configuration)
        {
            _categoryService = categoryService;
            _articleService = articleService;
            _commentService = commentService;
            _userContext = userContext;
            _configuration = configuration;
        }

        public IActionResult Index(int indexPage = 1)
        {
            var dto = new ArticlePagerDto()
            {
                PageIndex = indexPage,
                PageSize = 10
            };

            return View("Index", GetIndexView(dto));
        }

        public IActionResult Search(string keyword = "", int searchPage = 1)
        {
            var dto = new ArticlePagerDto()
            {
                Keyword = keyword,
                PageIndex = searchPage,
                PageSize = 10
            };

            return View("Index", GetIndexView(dto));
        }

        public IActionResult Tag(int id, int tagPage = 1)
        {
            var dto = new ArticlePagerDto()
            {
                TagId = id,
                PageIndex = tagPage,
                PageSize = 10
            };

            return View("Index", GetIndexView(dto));
        }

        public IActionResult Category(int categoryId = 0, int categoryPage = 1)
        {
            var dto = new ArticlePagerDto()
            {
                CategoryId = categoryId,
                PageIndex = categoryPage,
                PageSize = 10
            };

            return View("Index", GetIndexView(dto));
        }

        public IActionResult Archive(int year = 0, int month = 0, int archivePage = 1)
        {
            var dto = new ArticlePagerDto()
            {
                Year = year,
                Month = month,
                PageIndex = archivePage,
                PageSize = 10
            };

            return View("Index", GetIndexView(dto));
        }

        public new IActionResult User(int userId=0, int userPage = 1)
        {
            var dto = new ArticlePagerDto()
            {
                UserId = userId,
                PageIndex = userPage,
                PageSize = 10
            };

            return View("Index", GetIndexView(dto));
        }

        private IndexView GetIndexView(ArticlePagerDto dto)
        {
            if (dto.PageIndex < 1)
            {
                dto.PageIndex = 1;
            }
            var pageinfo = _articleService.GetPageInfo(dto);

            var model = new IndexView()
            {
                TagId = dto.TagId,
                UserId = dto.UserId,
                CategoryId = dto.CategoryId,
                Year = dto.Year,
                Month = dto.Month,
                PageInfo = pageinfo,
                CategoryList = _categoryService.GetCategoryList(),
                Keyword = dto.Keyword,
                ArchiveList = _articleService.GetArchiveList(),
                TagList = _articleService.GetTagList()
            };

            model.SeoTitle = _configuration.GetSection("Seo").GetValue<string>("Title");
            model.SeoKeywords = _configuration.GetSection("Seo").GetValue<string>("Keywords"); 
            model.SeoDescription = _configuration.GetSection("Seo").GetValue<string>("Description"); 


            if (!string.IsNullOrEmpty(dto.Keyword))
            {
                model.SeoTitle = "搜索："+ dto.Keyword;
            }
            else if (dto.CategoryId>0)
            {
                var cate = model.CategoryList.FirstOrDefault(p => p.Id == model.CategoryId) ?? new CategoryEntity { Name = "默认分类" };
                model.SeoTitle = "分类：" + cate.Name;
                model.SeoKeywords = cate.SeoKeywords;
                model.SeoDescription = cate.SeoDescription;
            }
            else if (dto.Year > 0 && dto.Month > 0)
            {
                model.SeoTitle = "归档：" + dto.Year + "年" + dto.Month + "月";
            }
            else if (dto.Year > 0)
            {
                model.SeoTitle = "归档：" + dto.Year + "年";
            }
            else if (dto.TagId > 0)
            {
                var tag = model.TagList.FirstOrDefault(p => p.Id == model.TagId) ?? new TagDto { Name = "标签" };
                model.SeoTitle = "标签：" + tag.Name;
            }






            return model;
        }

        public ActionResult Detail(int id)
        {
            var model = new DetailView()
            {
                Article = _articleService.GetArticle(id)
            };

            if (model.Article == null)
            {
                return RedirectToAction("Index");
            }

            model.Category = _categoryService.GetCategory(model.Article.CategoryId);

            _articleService.UpdateReadCount(model.Article);

            model.SeoTitle = model.Article.Title;
            model.SeoKeywords = model.Article.Tag;
            if (!string.IsNullOrEmpty(model.Article.Summary))
            {
                model.SeoDescription = model.Article.Summary.Replace("\n", "").Replace(" ", "").Replace("\t", "").Replace("\r", "");
            }

            model.LoginInfo = _userContext.CurrentUser.MapTo<LoginInfo>();

            return View(model);
        }

        [HttpPost]
        public ActionResult AddComment(CommentAddDto dto)
        {
            var loginInfo = _userContext.CurrentUser;
            return Json(_commentService.Add(dto, loginInfo.MapTo<LoginInfo>()));
        }


        [HttpPost]
        public ActionResult GetCommentPageInfo(CommentPagerDto dto)
        {
            dto.Status = CommentStatusEnum.Normal;
            return Json(new ResultDto
            {
                Status = true,
                Data = _commentService.GetPageInfo(dto)
            });
        }
    }
}